package com.xiecong.filter;

import com.xiecong.pojo.Emp;
import com.xiecong.utils.CurrentHolder;
import com.xiecong.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * 令牌校验过滤器
 */
@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //类型强制转换
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1. 获取请求uri
        String requestURI = request.getRequestURI();
        //2. 判断请求uri中是否包含login，如果包含，说明是登录操作，放行
        if (requestURI.contains("login")) {
            log.info("登录操作，放行");
            filterChain.doFilter(request, response);
            return;
        }
        //3. 获取请求头中的令牌（token）
        String token = request.getHeader("token");
        //4. 判断令牌是否存在，如果不存在，响应 401
        if (!StringUtils.hasLength(token)) {
            log.info("令牌不存在，响应401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            //response.setStatus(401);
            return;
        }
        //5. 解析token，如果解析失败，响应 401
        try {
            Claims claims = JwtUtils.parseJWT(token);
            // 从token中获取id
            Integer id = claims.get("id", Integer.class);
            // 将id保存到ThreadLocal中
            //CurrentHolder.setCurrentId(id);
            // 从token中获取name
            String name = claims.get("name", String.class);
            Emp emp = new Emp();
            emp.setId(id);
            emp.setName(name);
            CurrentHolder.setCurrentEmp(emp);
        } catch (Exception e) {
            log.error("令牌解析失败");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        //6. 放行
        log.info("令牌合法，放行");
        filterChain.doFilter(request, response);
        //7. 释放资源,清空ThreadLocal中保存的当前用户信息（id、name）
        CurrentHolder.remove();
    }
}
